package longestCommonPrefix;

/*  编写一个函数来查找字符串数组中的最长公共前缀。
    如果不存在公共前缀，返回空字符串 ""。

    输入：strs = ["flower","flow","flight", "fl"]
    输出："fl"


    输入：strs = ["dog","racecar","car"]
    输出：""
    解释：输入不存在公共前缀。
*/

class Solution1 {
    public static String longestCommonPrefix(String[] strs) {
        // 最短字符串
        String shortStr = strs[0];
        int index = 0;
        boolean success = true;
        // 遍历收个数据字符
        for (int j = 0; j < shortStr.length(); j++) {
            for (int i = 1; i < strs.length; i++) {
                if (strs[i].length() >= j+1 && shortStr.charAt(j) == strs[i].charAt(j)) {
                    continue;
                }
                success = false;
                break;
            }
            if (success) {
                index = j + 1;
            } else {
                return shortStr.substring(0, j);
            }
        }
        return shortStr.substring(0, index);
    }

    public static void main(String[] args) {
        String[] strs = {"f","q", "f"};
        System.out.println(longestCommonPrefix(strs));
    }
}